package com.eagle.security.interceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TestInterceptor implements HandlerInterceptor {

    private final static Logger log = Logger.getLogger(TestInterceptor.class);
    ThreadLocal<Long> usetime = new ThreadLocal<Long>();
    
	@PostConstruct
	public void test(){
		System.out.println("init TestInterceptor");
	}
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	    Long before = usetime.get();
        Long now = System.nanoTime();
        long u = (now - before)/1000000 ;
        
        log.info(arg0.getRequestURL()+",请求花费时间(毫秒):" + u );		
	}

	/**
	 * 从controller出来返回
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	    Long before = usetime.get();
	    Long now = System.nanoTime();
	    long u = (now - before)/1000000 ;
	    if(arg3!=null){
	    	log.info("name="+arg3.getViewName()+",control花费时间(毫秒):" + u );
	    }else{
	    	log.info("name="+arg3+",control花费时间(毫秒):" + u );
	    }
	}

	/**
	 * 进入controller之前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
        usetime.set(System.nanoTime());
		return true;
	}
	
}
